package com.dayuanit.atm.controller;

import com.dayuanit.atm.dto.ResponseDTO;
import com.dayuanit.atm.entity.User;
import com.dayuanit.atm.handler.WxAuthenHandler;
import com.dayuanit.atm.holder.WxAccessTokenHolder;
import com.dayuanit.atm.holder.WxUserInfoHolder;
import com.dayuanit.atm.service.WxBindService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class WxController extends BaseController {

    @Autowired
    private WxBindService wxBindService;

    @Autowired
    private WxAuthenHandler wxAuthenHandler;

    @RequestMapping("/wx/getCodeUrl")
    @ResponseBody
    public ResponseDTO getCodeUrl() {
        return ResponseDTO.success(wxAuthenHandler.getCodeUrl());
    }

    @RequestMapping("/wx/wxCallBack")
    public String wxCallBack(String code, HttpServletRequest request, HttpSession session) {
        System.out.println(">>>>>>>>>>>>>wxCallBack() code=" + code);

        //获取access_token
        WxAccessTokenHolder wxAccessTokenHolder = wxAuthenHandler.getAccessToken(code);

        //再通过access_token获取用户信息
        WxUserInfoHolder wxUserInfo = wxAuthenHandler.getWxUserInfo(wxAccessTokenHolder);

        session.setAttribute("headimgurl", wxUserInfo.getHeadimgurl());
        session.setAttribute("nickName", wxUserInfo.getNickname());
        session.setAttribute("openid", wxAccessTokenHolder.getOpenid());

        //向绑定表插入数据
        User user = wxBindService.saveWxInfo(wxUserInfo);
        if (null != user) {
            //登录 然后重新定向到个人中心页面
            session.setAttribute("loginUser", user);
            return "redirect:/user/toHome.do";
        } else {
            return "redirect:/wx/bindPage.do";
        }
    }

    @RequestMapping("/wx/bindPage")
    public String bindPage() {
        return "bindLogin";
    }

    @RequestMapping("/wx/wxBind")
    @ResponseBody
    public ResponseDTO wxBind(String username, String pwd, HttpSession session) {
        Object obj = session.getAttribute("openid");
        if (null == obj) {
            return ResponseDTO.fail("绑定失败");
        }

        User user = wxBindService.processBind(username, pwd, obj.toString());
        session.setAttribute("loginUser", user);

        return ResponseDTO.success();
    }
}
